package com.epam.rd.classloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyLoader extends ClassLoader {

    private String dirPath;

    public MyLoader(ClassLoader parent, String dirPath) {
        super(parent);
        this.dirPath = dirPath;
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> result;
        try {
            byte[] binary = readFile(dirPath + name + ".class");
            System.out.println("Start loading class name: " + name
                    + " from dir: " + dirPath);
            result = defineClass(name, binary, 0, binary.length);
            System.out.println("Complete loading class name: " + name
                    + " from dir: " + dirPath);
        } catch (IOException e) {
            System.out.println("Loading class with super-loader");
            result = super.findClass(name);
        }
        return result;
    }

    private byte[] readFile(String path) throws IOException {
        File file = new File(path);
        InputStream inputStream = null;
        byte[] data = new byte[(int) file.length()];
        try {
            inputStream = new FileInputStream(file);
            inputStream.read(data, 0, data.length);
        } finally {
            inputStream.close();
        }
        System.out.println("reading from file: " + path);
        return data;
    }

}
